package objects.slots;

import objects.DataObject;
import objects.fields.ObjectArray;

public class ArraySlot extends Slot {
	int index;
	Position position;
	ObjectArray object;
	
	public ArraySlot( ObjectArray object, int index, Position position ) {
		this.object = object;
		this.index = index;
		this.position = position;
	}

	@Override
	public void insert( DataObject value ) {
		DataObject[] array = object.value;
		DataObject[] newArray = new DataObject[ array.length + 1 ];
		switch( position ) {
			case BEFORE:
				for( int n = 0; n < index; n++ ) newArray[ n ] = array[ n ];
				for( int n = index; n < array.length; n++ ) newArray[ n + 1 ] = array[ n ];
				newArray[ index ] = value;
				object.value = newArray;
				break;
			case INSTEAD:
				object.value[ index ] = value;
				break;
			case AFTER:
				for( int n = 0; n < index + 1; n++ ) newArray[ n ] = array[ n ];
				for( int n = index + 1; n < array.length; n++ ) newArray[ n + 1 ] = array[ n ];
				newArray[ index + 1 ] = value;
				object.value = newArray;
				break;
		}		
	}

	@Override
	public DataObject remove() {
		DataObject[] array = object.value;
		DataObject[] newArray = new DataObject[ array.length - 1 ];
		DataObject value = array[ index ];
		for( int n = 0; n < index; n++ ) newArray[ n ] = array[ n ];
		for( int n = index + 1; n < array.length; n++ ) newArray[ n - 1 ] = array[ n ];
		object.value = newArray;
		return value;
	}
}
